package com.example.k12.http

import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object NetworkRequest {

        const val baseUrl = "https://k12.tgkj.cloud"
//    const val baseUrl = "https://k12.tgkj.cloud"

    private val okHttp = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .addInterceptor(HttpLoggingInterceptor())
        .build()

    private val retrofit = Retrofit.Builder()
        .baseUrl(baseUrl)   // 替换成你的真实域名
        .client(okHttp)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    // 对外只暴露一个 service
    val api: ApiService = retrofit.create(ApiService::class.java)
}


suspend fun <T> safeApiCall(apiCall: suspend () -> ApiResponse<T>): Result<T> {
    return withContext(Dispatchers.IO) {
        try {
            val response = apiCall()
            if (response.code == 0) { // 假设0为成功码
                if (response.data != null) {
                    Result.success(response.data)
                } else {
                    Result.failure(Exception("返回数据为空"))
                }
            } else {
                Result.failure(Exception(response.msg ?: "未知错误"))
            }
        } catch (e: Exception) {
            Result.failure<T>(e)
        }
    }
}

// 专门用于处理可能类型不匹配的 API 调用
suspend inline fun <reified T : Any> safeApiCallWithCast(crossinline apiCall: suspend () -> ApiResponse<*>): Result<T> {
    return withContext(Dispatchers.IO) {
        try {
            val response = apiCall()
            if (response.code == 0) {
                when (val data = response.data) {
                    null -> Result.failure(Exception("返回数据为空"))
                    is T -> {
                        // 处理List类型的特殊情况
                        if (T::class.java.isAssignableFrom(List::class.java) &&
                            data is List<*>
                        ) {
                            // 尝试通过 Gson 重新解析
                            val gson = Gson()
                            val json = gson.toJson(data)
                            // 对于List类型，需要特殊处理泛型参数
                            val type = object : com.google.gson.reflect.TypeToken<T>() {}.type
                            val castedData = gson.fromJson<T>(json, type)
                            Result.success(castedData)
                        } else {
                            Result.success(data)
                        }
                    }

                    else -> {
                        try {
                            // 尝试通过 Gson 重新解析
                            val gson = Gson()
                            val json = gson.toJson(data)
                            // 处理List类型的特殊情况
                            val castedData = if (T::class.java.isAssignableFrom(List::class.java) &&
                                data is List<*>
                            ) {
                                // 对于List类型，需要特殊处理泛型参数
                                val type = object : com.google.gson.reflect.TypeToken<T>() {}.type
                                gson.fromJson<T>(json, type)
                            } else {
                                gson.fromJson(json, T::class.java)
                            }

                            Result.success(castedData)
                        } catch (e: JsonSyntaxException) {
                            Result.failure(Exception("数据转换失败: ${e.message}"))
                        } catch (e: Exception) {
                            Result.failure(Exception("数据转换异常: ${e.message}"))
                        }
                    }
                }
            } else {
                Result.failure(Exception(response.msg ?: "未知错误"))
            }
        } catch (e: Exception) {
            Result.failure<T>(e)
        }
    }
}


// Result扩展函数，用于解构
operator fun <T> Result<T>.component1(): T? = getOrNull()
operator fun <T> Result<T>.component2(): Throwable? = exceptionOrNull()
